/* erl_comm.c */
/*
gcc -o extprg -I/usr/local/lib/erlang/lib/erl_interface-3.5.9/include/ \
 -L/usr/local/lib/erlang/lib/erl_interface-3.5.9/lib/ \
  complex.c erl_comm.c ei.c \
   -lerl_interface -lei -lpthread
*/
#define PACKET_N 4

typedef unsigned char byte;

read_cmd(byte *buf){
    unsigned long len;

    if (read_exact(buf, 4) != 4)
        return(-1);
    len = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
    return read_exact(buf, len);
}

write_cmd(byte *buf, unsigned long len) {
    byte li;
    
    li = (len >> 24) & 0xff;
    write_exact(&li, 1);

    li = (len >> 16) & 0xff;
    write_exact(&li, 1);

    li = (len >> 8) & 0xff;
    write_exact(&li, 1);
  
    li = len & 0xff;
    write_exact(&li, 1);

    return write_exact(buf, len);
}

read_exact(byte *buf, int len) {
    int i, got=0;

    do {
        if ((i = read(0, buf+got, len-got)) <= 0)
            return(i);
        got += i;
    } while (got<len);

    return(len);
}

write_exact(byte *buf, int len) {
    int i, wrote = 0;

    do {
        if ((i = write(1, buf+wrote, len-wrote)) <= 0)
            return (i);
        wrote += i;
    } while (wrote<len);

    return (len);
}

